#include "xmlobject.h"

using namespace bt;

bool XMLObject::loadFromXML(xmlDoc* doc, xmlNode* node)
{	/* stub for virtual */
	xmlSaveFile("-", doc);
}
		
void XMLObject::writeToXML(xmlDoc* doc, xmlNode* node) { /* stub for virtual */ }

bool XMLObject::loadFromXMLFile(const char* filename)
{
	Uint8* buffer;
	PHYSFS_sint64 filesize = FS_readFile(buffer, filename);
	
	/*
	 * Checks if file loaded correctly and
	 * attempts to parse the xml
	 */
	if(buffer)
	{
		std::string strbuff = (char*)buffer;
		
		xmlDoc* doc = xmlParseMemory(strbuff.c_str(), filesize);
		
		if(doc)
		{
			xmlNode* node = xmlDocGetRootElement(doc);
			
			loadFromXML(doc, node);
			
			xmlFreeDoc(doc);
		}
		else
		{
			fprintf(stderr, "XML: Unable to parse file %s\n", filename);
			return false;
		}
	}
	else /* !buffer */
	{
		fprintf(stderr, "XML: Unable to load file %s\n", filename);
		return false;
	}
	
	// Clean up loaded file
	delete [] buffer;
}

bool XMLObject::writeToXMLFile(const char* filename)
{
}

std::string bt::XML_getPropString(xmlNode* node, const char* name)
{
	std::string propString;
	
	xmlChar* prop = xmlGetProp(node, (xmlChar*) name);
	
	if(prop)
	{
		propString = (const char*)prop;
		trimString(propString);
	}
	
	xmlFree(prop);
	
	return propString;
}

int bt::XML_getPropInt(xmlNode* node, const char* name)
{
	std::string propString;
	
	// Get the string for the integer
	xmlChar* prop = xmlGetProp(node, (xmlChar*) name);
	
	if(prop)
	{
		propString = (const char*)prop;
		trimString(propString);
	}
	else
		return 0;
	
	xmlFree(prop);
	
	// Convert the string to a base 10 integer
	int propInt = strtol(propString.c_str(), NULL, 10);
	
	return propInt;
}

float bt::XML_getPropFloat(xmlNode* node, const char* name)
{
	std::string propString;
	
	// Get the string for the float
	xmlChar* prop = xmlGetProp(node, (xmlChar*) name);
	
	if(prop)
	{
		propString = (const char*)prop;
		trimString(propString);
	}
	else
		return 0;
	
	xmlFree(prop);
	
	// Convert the string to a base 10 integer
	float propFloat = strtod(propString.c_str(), NULL);
	
	return propFloat;
}

std::string bt::XML_getContentString(xmlNode* node)
{
	std::string contentString;
	
	const char* content = (const char*)node->content;
	
	if(content)
	{
		contentString = content;
		trimString(contentString);
	}
	
	return contentString;
}

